'use strict';
seajs.use(['bootstrap.min.js','dist/messages_cn.js']);
// 扩展校验方法-非法字符验证

seajs.use('dist/jquery.validate.min.js',function(){
    if(jQuery.validator != undefined && jQuery.validator.length > 0) {
        jQuery.validator.addMethod("isLegalCharacter", function(value, element) {
                var regPattern = /^[^\|<>]*$/;
                return this.optional(element) || (regPattern.test(value));
            }, "有奇怪的字符出现哦~~");
        jQuery.validator.addMethod("isNameCharacter", function(value, element) {
            var regPattern = /^([\u4e00-\u9fa5a-zA-Z]{2,16})$/;
            return this.optional(element) || (regPattern.test(value));
        }, "仅支持(2-16位)中文字、英文字母");
            // [a-zA-Z]{1,20}|[\u4e00-\u9fa5]{1,10}
        jQuery.validator.addMethod("email", function(value, element) {
                var regPattern = /^([a-zA-Z0-9\._-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
                return this.optional(element) || (regPattern.test(value));
            }, "请输入正确格式的邮箱地址");
        jQuery.validator.addMethod("regexPassword", function(value, element) {  
            return this.optional(element) || /^(?=^.{6,}$)((?=.*\d)|(?=.*\W+))(?=.*[A-Za-z]).*$/.test(value);  
        }, "一个字母，一个数字");
        jQuery.validator.addMethod("mobile", function(value, element) {  
            var regPattern = /^1\d{10}$/;//手机号验证
            return this.optional(element) || regPattern.test(value);  
        }, "请输入正确格式的手机号码");
        jQuery.validator.addMethod("contact", function(value, element) {  
            var regPattern = /^1\d{10}$/,//手机号验证
                regPattern2 = /^([a-zA-Z0-9\._-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;//邮箱验证
            return this.optional(element) || regPattern.test(value) || regPattern2.test(value);  
        }, "请输入正确格式的手机号码或者邮箱帐号");
        jQuery.validator.addMethod("CN", function(value, element) {  
            var regPattern = /^[\u4e00-\u9fa5]+$/;//中文验证
            return this.optional(element) || regPattern.test(value);  
        }, "请输入中文");
        jQuery.validator.addMethod("idcard", function(value, element) {  
            var regPattern1 = /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/,//大陆身份证号码验证
                regPattern2=/^((\s?[A-Za-z])|([A-Za-z]{2}))\d{6}(\([0-9aA]\)|([0-9aA]))$/,//香港身份证号码验证
                regPattern3=/^[A-Za-z]{1}[0-9]{9}$/,//台湾省身份证号码验证
                regPattern4=/^[1|5|7][0-9]{6}\([0-9Aa]\)/,//澳门身份证号码验证
                regPattern5=/^[A-Za-z]{1}[0-9]{8}$/,//护照验证
                s2=/^[0-9]{8}$/;//台胞身份证号验证
            return this.optional(element) || regPattern1.test(value) || regPattern2.test(value) || regPattern3.test(value) || regPattern4.test(value) || regPattern5.test(value) || s2.test(value);  
        }, "请输入正确格式的身份证号");
        jQuery.validator.addMethod("edl", function(value, element) {  
            var regPattern = /^[a-zA-Z0-9][a-zA-Z0-9_]*$/;//
            return this.optional(element) || regPattern.test(value);  
        }, "只能输入英文、数字、下划线(英文或数字开头)");
        jQuery.validator.addMethod("telnumber", function(value, element) {  
                var regPattern1 = /^1\d{10}$/,//手机号验证
                    //regPattern2 = /^0\d{2,3}-?\d{7,8}$/;//座机号验证
                    regPattern2 = /([0-9]{3,4}-)?[0-9]{7,8}/;//座机号验证
                return this.optional(element) || regPattern1.test(value) || regPattern2.test(value);  
            }, "请输入正确格式的电话号码");
    }
});

(function(window){
    var _window=window;
    /* 历史遗留原因声明全局变量 ╮(￣▽￣")╭") */
    _window.len = 0;
    _window.i=0;
    _window.num = 0;
    _window.postData = 0;
    _window.param = 0;
    _window.$parent=0;
    _window.$submit=0;
    _window.$popMask = $('#popMask');
    _window.$html = $('html');
    _window.$win=$(_window);
    _window.$popModal = $('.js_pop_modal');
    _window.$popModalContent = $('#popModalContent');
    _window.errorHtml = '<dl class="lg-web-error"><dt>Oops~网络错误</dt><dd>出现了网络错误，请检查您的网络是否正常⊙﹏⊙</dd></dl>';
        /* 通用弹窗变量 */
    _window.$ajaxMessageBox = $('#ajaxMessageBox');
    _window.$ajaxMessage = $('#ajaxMessage');
    _window.$promptMessageBox = $('#promptMessageBox');
    _window.$promptMessage = $('#promptMessage');
    _window.$promptConfirmBtn = $('#promptConfirmBtn');
    _window.$popClose = $('.js_pop_close');
    _window.isConfirm = true;
    /* relate search */
    _window.arrList=0;
    _window.arrHtml=0;
    _window.arrContest=0;
    _window.arrPublicUsers=0;
    _window.arrUsers=0;
    _window.cLen=0;
    _window.pLen=0;
    _window.uLen=0;
    _window.oHtml=0;
    _window.strHtml=0;
    _window.childDom=0;
    _window.result=0;
    _window.regSpace = /(^\s+)|(\s+$)/g;//校验内容前后正则
    _window.regAllSpace = /\ +/g;//校验内容所有空格
    _window.regEnter = /[\r\n]/g;//校验换行
    _window.regLegal = /^[^\|<>]*$/;//校验非法字符正则
    /* add tag */
    _window.commonTagTpl = '';
    _window.$commonFormTag =$('#J_commonFormTag');
    _window.commonFormTagDom = $commonFormTag[0];
    _window.$commonTagWrap=0;
    _window.$commonTagValueInput=0;
    _window.$tag=0;
    _window.val=0;
    _window.url=0;
    _window.sid=0;
    //_window.name=0;
    _window.wid=0;
    _window.pid=0;
    _window.cid=0;
    _window.intervalid=0;
    _window.isAct=0;
    _window.strText=0;
    _window.regPattern=0;
    //_window.time=0;
    _window.isLegal=0;
    _window.pureContent=0;
    _window.dropDownFun = {//模拟下拉菜单方法
            dropDownOpt:function(){
                //模拟下拉菜单点击功能
                var self = this,
                    $html=$('html');
                $html.off('click','.dropdown-option').on('click','.dropdown-option',function(){
                    
                    var $t = $(this),
                        optionTxt=$t.text(),
                        optionVal=$t.attr('value');
                    $t.parents('.dropdown').find('.dropdown-toggle em').addClass('select-value').text(optionTxt);
                    $t.parents('.dropdown').find('input').attr('value',optionVal);
                });
            },
            htmlRender:function(data){ //下拉框列表渲染
                //参数fda 为选项值，参数fdb 为属性tabindex的值
        		var self=this,
        			html = '';
        		$.each(data,function(i,item){
        			html += ''+'<li role="presentation"><a href="javascript:;" role="menuitem" value="'+item.hid+'" title="'+item.hname+'" tabindex="'+item.hid+'" class="dropdown-option">'+item.hname+'</a></li>';
        		});
        		return html;
            },
            casDropDown:function(){//级联下拉菜单
                var self = this;
                seajs.use(['lib/homeTownList.js','lib/monthDayList.js'],function(){
                    var cascadingList = {//级联下拉菜单id及请求数据列表
                        //参数fdata为一级列表数据，参数dsdata为二级列表默认显示数据
                        /*"0":{"fid":"#regProvinceUl","sid":"#regCityUl","fdata":homeTownList,"dsdata":homeTownList[110000].child},
                        "1":{"fid":"#homeProvinceUl","sid":"#homeCityUl","fdata":homeTownList,"dsdata":homeTownList[110000].child},*/
                        "0":{"fid":"#inProvinceUl","sid":"#inCityUl","fdata":homeTownList,"dsdata":homeTownList[110000].child}/*,
                        "3":{"fid":"#pwGCBirthMonthUl","sid":"#pwGCBirthDayUl","fdata":gcMonthDayList,"dsdata":gcMonthDayList[1].child},
                        "4":{"fid":"#pwCCBirthMonthUl","sid":"#pwCCBirthDayUl","fdata":ccMonthDayList,"dsdata":ccMonthDayList[1].child}*/
                    };
                    if(cascadingList){
                        $.each(cascadingList,function(i,item){
                            var fdata = item.fdata,
                                dsdata = item.dsdata,
                                fid = item.fid,
                                sid = item.sid;
                            if(fdata){
                                var fDataHtml = self.htmlRender(fdata),
                                    $fidDom = $(fid)[0];
                                //$(item.fid).html(self.htmlRender(fdata));//渲染一级列表
                                if($fidDom){
                                    $fidDom.innerHTML = fDataHtml;//渲染一级列表
                                }
                            }
                            if(dsdata){
                                var dsDataHtml = self.htmlRender(dsdata),
                                    $sidDom = $(sid)[0];
                                //$(item.sid).html(self.htmlRender(dsdata));//默认渲染二级列表
                                if($sidDom){
                                    $sidDom.innerHTML = dsDataHtml;//默认渲染二级列表
                                }
                                
                            }

                            if(fdata){
                                $(fid).off('click').on('click','.dropdown-option',function(){
                                        var $self = $(this),
                                            optionTxt=$self.text(),
                                            optionVal = $self.attr('value'),
                                            tabindex = $self.attr('tabindex'),
                                            fChildData = fdata[tabindex].child,
                                            fChildHtml = self.htmlRender(fChildData),
                                            sidDOM = $self.parents('.common-form-line').find(sid),
                                            $sidDom = sidDOM[0],
                                            $selfDropDownEm = $self.parents('.dropdown').find('.dropdown-toggle em'),
                                            $selfDropDownInp = $self.parents('.dropdown').find('.dropdown-toggle input');
                                            
                                        //sidDOM为子级下拉菜单元素对象集合,$selfDropDownEm为父级下拉菜单内容值对象集合，$sidDropDownEm为子级下拉菜单内容值对象集合
                                        //给父级下拉菜单赋值
                                        $selfDropDownEm.addClass('select-value').text(optionTxt);
                                        $selfDropDownInp.attr('value',optionVal);
                                        //$self.parents('.dropdown').find('.dropdown-toggle em').addClass('select-value').text(optionTxt);
                                        //$(this).parents('.common-form-line').find(sid).html(self.htmlRender(fdata[tabindex].child));
                                        //$(this).parents('.common-form-line').find(sid).html(fChildHtml);
                                        //var sidDOM = $(this).parents('.common-form-line').find(sid);
                                        if($sidDom){//如果有子下拉菜单
                                            $sidDom.innerHTML = fChildHtml;
                                        }
                                        var secDefault = $self.parents('.common-form-line').find(sid+' li:first .dropdown-option').text(),
                                            secVal = $self.parents('.common-form-line').find(sid+' li:first .dropdown-option').attr('value'),
                                            $sidDropDownEm = sidDOM.parents('.dropdown').find('.dropdown-toggle em'),
                                            $sidDropDownInp = sidDOM.parents('.dropdown').find('.dropdown-toggle input');
                                        //给子级下拉菜单赋值
                                        $sidDropDownEm.addClass('select-value').text(secDefault);
                                        $sidDropDownInp.attr('value',secVal);
                                        //var secDefault = $(this).parents('.common-form-line').find(sid+' li:first .dropdown-option').text();
                                        //sidDOM.parents('.dropdown').find('.dropdown-toggle em').addClass('select-value').text(secDefault);

                                });
                            }
                        });
                    }
                });
            },
            init:function(){
                var self=this;
                self.dropDownOpt();//执行下拉菜单点击效果
            }
        };
    _window.popToggle = {
            popOpen : function(){
                //callBack为回调函数
                var self = this,
                    $html = $('html'),
                    popTarget,
                    $popMask = $('#popMask');
                $html.off('click','.js_pop_open').on('click','.js_pop_open',function(){
                    var $t = $(this);
                    popTarget = $t.attr('pop-target');
                    $('#'+popTarget).fadeIn();
                    $popMask.fadeIn();
                });
            },
            popClose : function(){
                var self = this,
                    $html = $('html'),
                    $popMask=$('#popMask');
                $html.off('click','.js_pop_close').on('click','.js_pop_close',function(){
                    $(this).parents('.js_pop_modal').fadeOut();
                    $popMask.fadeOut();
                });
            },
            init:function(){
                var self = this;
                self.popOpen();
                self.popClose();
            }
        };
    _window.WJ = {
            length: function( val, is_byte ){
                var length = 0;
                if (!val) { return length; }
                for (var i = 0,  strLen = val.length; i < strLen; i++) {
                    if (is_byte && val.charCodeAt(i) > 255) {
                        length = length + 2;
                    } else {
                        length = length + 1;
                    }
                }
                return length;
            },
            // Simple JavaScript Templating
            // John Resig - http://ejohn.org/ - MIT Licensed
            template: function(str, data){
                // Generate a reusable function that will serve as a template
                // generator (and which will be cached).
                var fn = new Function("obj",
                        "var p=[],print=function(){p.push.apply(p,arguments);};" +

                        // Introduce the data as local variables using with(){}
                        "with(obj){p.push('" +

                        // Convert the template into pure JavaScript
                        str
                            .replace(/[\r\t\n]/g, " ")
                            .split("<%").join("\t")
                            .replace(/((^|%>)[^\t]*)'/g, "$1\r")
                            .replace(/\t=(.*?)%>/g, "',$1,'")
                            .split("\t").join("');")
                            .split("%>").join("p.push('")
                            .split("\r").join("\\'") +
                        "');}return p.join('');");

                // Provide some basic currying to the user
                return data ? fn( data ) : fn;
            },
            parseURL: function () {
                var a = window.location;
                var url = a.href;
                return {
                    source: url,
                    protocol: a.protocol.replace(':', ''),
                    host: a.hostname,
                    port: a.port,
                    query: a.search,
                    params: (function () {
                        var ret = {},
                            seg = a.search.replace(/^\?/, '').split('&'),
                            len = seg.length,
                            i = 0,
                            s;
                        for (; i < len; i++) {
                            if (!seg[i]) {
                                continue;
                            }
                            s = seg[i].split('=');
                            ret[s[0]] = s[1];
                        }
                        return ret;
                    })(),
                    file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
                    hash: a.hash.replace('#', ''),
                    path: a.pathname.replace(/^([^\/])/, '/$1'),
                    relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
                    segments: a.pathname.replace(/^\//, '').split('/')
                };
            }
        };
    //提示窗口方法
    _window.ajax_message = function($msg,noMask) {
        var $ajaxMessageBox=$('#ajaxMessageBox'),
            $ajaxMessage=$('#ajaxMessage'),
            $popMask = $('#popMask');
        if($ajaxMessage[0]){
            $ajaxMessage[0].innerHTML = $msg;
            $ajaxMessageBox.fadeIn();
            if(!noMask){
                $popMask.fadeIn();
            }
        }
    };

    _window.labelToggle = function(){//文本框内容提示显示、隐藏方法
        var $html=$('html'),
            thisInputVal,
            thisHasError=false,
            len = 0;
        $html.off('click','.js_trend_label').on('click','.js_trend_label',function(){
            var $self = $(this),
                $selfInput = $self.parents('.js_input_txt').find('input');
            $self.hide();
            $selfInput.focus();
        });

        $html.off('focus','.js_input_txt input').on('focus','.js_input_txt input',function(){
            var $self = $(this),
                thisTrendLabel = $self.parent().find('.js_trend_label');//通用文本框label
                
            if(thisTrendLabel){
                thisTrendLabel.hide();
            };
        });
        $html.off('blur','.js_input_txt input').on('blur','.js_input_txt input',function(){
            var $self = $(this),
                thisTrendLabel = $self.parent().find('.js_trend_label');//通用文本框label 
            thisInputVal = $self.val(),
            thisHasError = $self.hasClass('error');
            len = thisInputVal.length;
            if(thisTrendLabel && len == 0 && (!thisHasError)){
                thisTrendLabel.show();
            }
        });
    };
    _window.toTopFun = function(){//回到顶部功能
        var $win=$(_window),
            $toUp = $('#toUp'),
            $bodyHtml = $('body,html'),
            scrollTimer=null;
        //在一定的时间之内，只执行一次scroll事件函数
        if (scrollTimer) {
            clearTimeout(scrollTimer);
        }
        scrollTimer = setTimeout(function(){
            $win.off('scroll').on('scroll',function(){
                var scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
                scrolltop>0?$toUp.addClass('show'):$toUp.removeClass('show');
            });
        },400);
        $toUp.off('click').on('click',function(){
            $bodyHtml.animate({scrollTop:0},200); 
        });
    };
    /*_window.changeNav = function(){//change nav
        var $skNav = $('#skNav'),
            $win = $('window');
        $win.scroll(function(){
            var scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
            scrolltop>246?$skNav.addClass('scroll-w'):$skNav.removeClass('scroll-w');
        });
    };*/
    _window.addTagFun = function(){//添加标签方法
        var $html=$('html'),
            commonTagTpl = '',
            $commonFormTag =$('#J_commonFormTag'),
            commonFormTagDom =  $commonFormTag[0],
            $commonTagWrap,
            $commonTagValueInput,
            len = 0,
            num = 0,
            $tag,val,url,sid,name,wid,pid,cid,intervalid,isAct,cLen,uLen,
            strText,regPattern,time,
            regSpace = /(^\s+)|(\s+$)/g,//校验内容前后正则
            regAllSpace = /\ +/g,//校验内容所有空格
            regEnter = /[\r\n]/g,//校验换行
            regLegal = /^[^\|<>]*$/,//校验非法字符正则
            isLegal,
            pureContent;
        if(commonFormTagDom){
            commonTagTpl=commonFormTagDom.innerHTML;
        }
        function addTag( val,name,$appendDom,$inputDom){

            pureContent = val.replace(regSpace,"");
            if(pureContent.length==0){
                return false;
            }
            isLegal = regLegal.test(pureContent);
            if(!isLegal){
                ajax_message('有奇怪的字符出现哦~');
                return false;
            }
            var tpl = WJ.template( commonTagTpl , {
                value: val,
                name : name
            });
            
            $appendDom.append(tpl);
            
            $inputDom.val('');
        };
        $html.off('click', '.js_add_tag').on('click', '.js_add_tag', function() {
            var $t = $(this),
                type = $t.attr('action-type'),
                regMobile = /^1\d{10}$/,//手机号验证
                isMobile,
                regTel = /([0-9]{3,4}-)?[0-9]{7,8}/,//座机号验证
                isTel,
                regEmail = /^([a-zA-Z0-9\._-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/,//邮箱校验
                isEmail;
            sid = $t.attr('action-sid');
            wid = $t.attr('action-wid');
            $commonTagValueInput = $('#'+sid);
            $commonTagWrap = $('#'+wid);
            len = $commonTagWrap.find('.js_tag').length;
            num = $t.attr('max-length');
            if(num && num <= len){
                strText = $t.attr('action-message');
                ajax_message(strText);
                return false;
            }else{
                val = $commonTagValueInput.val();
                name = $t.attr('action-name');
                cLen = WJ.length(val);
                uLen = $commonTagValueInput.attr('maxlength');
                if(uLen){//如果标签有字数限制
                    if(cLen > uLen){
                        return false;
                    }
                }
                if(type && type == 'telphone'){//如果标签类型为手机或座机号码
                    isMobile = regMobile.test(val);
                    isTel = regTel.test(val);
                    if(!isMobile && !isTel){
                        return false;
                    }
                }
                if(type && type == 'email'){//如果标签类型为邮箱
                    isEmail = regEmail.test(val);
                    if(!isEmail){
                        return false;
                    }
                }
                addTag(val,name,$commonTagWrap,$commonTagValueInput);
                return false;
            }

        }).off('click', '.js_del_tag').on('click', '.js_del_tag', function(event) {
            var $t = $(this);
            $t.parent().remove();
            return false;
        }).off('keydown', '.js_tagInput').on('keydown', '.js_tagInput', function(event) {
            var $t = $(this),
                type = $t.attr('action-type'),
                regMobile = /^1\d{10}$/,//手机号验证
                isMobile,
                regTel = /([0-9]{3,4}-)?[0-9]{7,8}/,//座机号验证
                isTel,
                regEmail = /^([a-zA-Z0-9\._-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/,//邮箱校验
                isEmail;
            val = $t.val();
            sid = $t.attr('id');
            wid = $t.attr('action-wid');
            name = $t.attr('action-name');
            $commonTagValueInput = $('#'+sid);
            $commonTagWrap = $('#'+wid);
            len = $commonTagWrap.find('.js_tag').length;
            num = $t.attr('max-length');
            if(num && num <= len){
                strText = $t.attr('action-message');
                ajax_message(strText);
                return false;
            }else{
                cLen = WJ.length(val);
                uLen = $t.attr('maxlength');
                if(uLen){//如果标签有字数限制
                    if(cLen > uLen){
                        return false;
                    }
                }
                if (event.which == 13) {
                    if(type && type == 'telphone'){//如果标签类型为手机或座机号码
                        isMobile = regMobile.test(val);
                        isTel = regTel.test(val);
                        if(!isMobile && !isTel){
                            return false;
                        }
                    }
                    if(type && type == 'email'){//如果标签类型为邮箱
                        isEmail = regEmail.test(val);
                        if(!isEmail){
                            return false;
                        }
                    }
                    addTag(val,name,$commonTagWrap,$commonTagValueInput);
                    return false;
                }
            }
            
        });
    };
    _window.popMaskClose = function(){
        var $popMask=$('#popMask'),
            $ajaxMessageBox=$('#ajaxMessageBox'),
            $popModal=$('.js_pop_modal');
        $popMask.off('click').on('click',function(){//点击浮层关闭错误弹窗
            $ajaxMessageBox.fadeOut();
            $popModal.fadeOut();
            $popMask.fadeOut();
        });
    };
    _window.relateSearchAct = function(){//联想搜索
        var $html = $('html'),
            arrList,arrHtml,arrContest,arrPublicUsers,arrUsers,cLen,pLen,uLen,oHtml,strHtml,childDom,result,url,val;
        $html.off('input','.js_search_inp').on('input','.js_search_inp',function(){
            var $t = $(this),
                $selfSearchBox = $t.parents('.js_search_box'),
                $selfContestListBox = $selfSearchBox.find('.js_contest_list_box'),
                $selfContestList = $selfSearchBox.find('.js_contest_list'),
                $selfPublicListBox = $selfSearchBox.find('.js_public_list_box'),
                $selfPublicList = $selfSearchBox.find('.js_public_list'),
                $selfUserListBox = $selfSearchBox.find('.js_user_list_box'),
                $selfUserList = $selfSearchBox.find('.js_user_list');
            val = $t.val();
            url = encodeURI('/search/acs?str='+val);
            $.ajax({
                url : url,
                type: 'get',
                dataType: 'json',
                success: function(r){
                    //
                    if ( r.code == 0 ) {
                        arrContest = r.data["contest"];
                        arrPublicUsers = r.data["public_users"];
                        arrUsers = r.data["users"];
                        cLen = arrContest.length;
                        pLen = arrPublicUsers.length;
                        uLen = arrUsers.length;
                        if(cLen > 0 || pLen > 0 || uLen > 0){
                            $selfSearchBox.find('.js_search_hint').addClass('show');
                        }else{
                            $selfSearchBox.find('.js_search_hint').removeClass('show');
                        }
                        if(cLen > 0){
                            $selfContestListBox.addClass('show');
                            //
                            arrHtml = [];
                            strHtml = '';
                            for(i=0;i<cLen;i++){
                                arrHtml.push('<div class="paragraph-box js_search_result_item"><p class="p-one js_search_result"><a href="/'+arrContest[i]['contest_url']+'" title="'+arrContest[i]['contest_name']+'">'+arrContest[i]['contest_name']+'</a></p><p class="p-two">'+arrContest[i]['organiser']+'</p></div>');
                            }
                            strHtml = arrHtml.join('');
                            if($selfContestList[0]){
                                $selfContestList[0].innerHTML = strHtml;
                            }
                            
                        }else{
                            $selfContestListBox.removeClass('show');
                        }
                        if(pLen > 0){
                            $selfPublicListBox.addClass('show');
                            //
                            arrHtml = [];
                            strHtml = '';
                            for(i=0;i<pLen;i++){
                                arrHtml.push('<div class="paragraph-box js_search_result_item clearfix"><a class="p-img fl" href="/u/'+arrPublicUsers[i]['uid']+'"><img src="'+arrPublicUsers[i]['avatar']+'"></a><span class="college js_search_result fl"><a href="/u/'+arrPublicUsers[i]['uid']+'" title="'+arrPublicUsers[i]['real_name']+'">'+arrPublicUsers[i]['real_name']+'</a></span></div>');
                            }
                            strHtml = arrHtml.join('');
                            if($selfPublicList[0]){
                                $selfPublicList[0].innerHTML = strHtml;
                            }
                        }else{
                            $selfPublicListBox.removeClass('show');
                        }
                        if(uLen > 0){
                            $selfUserListBox.addClass('show');
                            //
                            arrHtml = [];
                            strHtml = '';
                            for(i=0;i<uLen;i++){
                                arrHtml.push('<div class="paragraph-box js_search_result_item clearfix"><a class="p-img fl" href="/u/'+arrUsers[i]['uid']+'"><img src="'+arrUsers[i]['avatar']+'"></a><span class="college js_search_result fl"><a href="/u/'+arrUsers[i]['uid']+'" title="'+arrUsers[i]['real_name']+'">'+arrUsers[i]['real_name']+'</a></span></div>');
                            }
                            strHtml = arrHtml.join('');
                            if($selfUserList[0]){
                                $selfUserList[0].innerHTML = strHtml;
                            }
                        }else{
                            $selfUserListBox.removeClass('show');
                        }
                        
                    }else{
                        ajax_message(r.message);
                    }
                }
            });
        });
        $('body').off('click').on('click',function(e){//点击下拉菜单外部区域，关闭下拉菜单
            var target = $(e.target);
            if(target.closest('.js_search_hint').length == 0){
                $('.js_search_hint').removeClass('show');
            }
        });
        $html.off('click','.js_search_result_item').on('click','.js_search_result_item',function(){
            var $t = $(this);
            result = $t.find('.js_search_result').text();
            $t.parents('.js_search_box').find('.js_search_inp').val(result);
            $t.parents('.js_search_hint').removeClass('show');
        });
    };
    _window.inpFocusTipAct = function(){
        var $html=$('html'),val,$parent;
        $html.off('focus','.js_set_event_input').on('focus','.js_set_event_input',function(){
            var $t = $(this);
            $t.parent().find('.js_set_event_tip').fadeIn();
        });
        $html.off('blur','.js_set_event_input').on('blur','.js_set_event_input',function(){
            var $t = $(this);
            $t.parent().find('.js_set_event_tip').fadeOut();
        });
        $html.off('click','.js_set_val_btn').on('click','.js_set_val_btn',function(){
            var $t = $(this);
            $parent = $t.parent();
            val = $parent.find('.js_set_val').text();
            $parent.siblings('input.js_set_event_input').val(val);
        });
    };
    _window.selectSchoolAct = function(callback){//选择学校方法
        //callback为选择学校的回调函数
        /* select school */
        var $selectSchoolList = $('#selectSchoolList'),
            $selectSchoolPop = $('#selectSchoolPop'),
            $searchSchoolInp = $('#searchSchoolInp'),
            $noneSchoolTipForm = $('#noneSchoolTipForm'),
            $noneSchoolInp = $('#noneSchoolInp'),
            $searchSchoolForm = $('#searchSchoolForm'),
            $searchSchoolInp = $('#searchSchoolInp'),
            $schoolFeedBackTip = $('#schoolFeedBackTip'),
            $html = $('html'),
            $popMask = $('#popMask'),
            $ajaxMessageBox = $('#ajaxMessageBox'),
            cid,val,url,arrList,arrHtml,oHtml,strHtml,i=0,postData,len,uid,requestTimer,
            $submit;
        $html.off('click','.js_school_pop_open').on('click','.js_school_pop_open',function(){
            var $t = $(this);
            cid = $t.attr('id');
            $selectSchoolList.empty();
            $noneSchoolTipForm.removeClass('show');
            $selectSchoolPop.attr('inp-target',cid).fadeIn();
            $popMask.fadeIn();
            $searchSchoolInp.val('').focus();
        });
        $selectSchoolList.off('click','.js_school_item').on('click','.js_school_item',function(){
            var $t = $(this);
            $selectSchoolList.find('li.js_school_item').removeClass('active');
            $t.addClass('active');
            val = $t.text();
            uid = $t.attr('univs-id');
            cid = '#'+$selectSchoolPop.attr('inp-target');
            $selectSchoolPop.fadeOut();
            $popMask.fadeOut();
            $(cid).val(val).attr('univs-id',uid).focus();
            if(callback){
                callback();
            }
        });
        function requestSchool(val,tip){
            //url = '/school/asu?univs_name='+val;
            url = encodeURI('/school/asu?univs_name='+val);
            $.ajax({
                url : url,
                type: 'get',
                dataType: 'json',
                success: function(r){
                    //
                    if ( r.code == 0 ) {
                        arrList = [];
                        arrHtml = [];
                        arrList = r.data.univs;
                        len = arrList.length;
                        if(len > 0){
                            $noneSchoolTipForm.removeClass('show');
                            for(i=0;i<len;i++){
                                oHtml = '<li class="mtv-set-scl-item js_school_item" univs-id="'+arrList[i]['univs_id']+'">'+arrList[i]['univs_name']+'</li>';
                                arrHtml.push(oHtml);
                            }
                            strHtml = arrHtml.join('');
                            if($selectSchoolList[0]){
                                $selectSchoolList[0].innerHTML = strHtml;
                            }
                        }else{
                            if(tip){//显示空内容提示
                                $noneSchoolInp.val(val);
                                $noneSchoolTipForm.addClass('show');
                            }
                        }
                    }else{
                        ajax_message(r.message,true);
                        setTimeout(function(){
                            $ajaxMessageBox.fadeOut();
                        },1000);
                    }
                },
                error : function(){
                    ajax_message(errorHtml,true);
                    setTimeout(function(){
                        $ajaxMessageBox.fadeOut();
                    },1000);
                }
            });
        };
        $searchSchoolInp.off('input').on('input',function(){
            var $t = $(this);
            val = $t.val();
            if(requestTimer){
                clearTimeout(requestTimer)
            }
            requestTimer=setTimeout(function(){
                requestSchool(val);//请求搜索学校接口
            },400);
        });
        seajs.use('dist/jquery.validate.min.js',function(){
            $searchSchoolForm.validate({
                submitHandler : function(){
                    val = $searchSchoolInp.val();
                    $selectSchoolList.empty();
                    requestSchool(val,true);//请求搜索学校接口
                    return false;
                }
            });
            $noneSchoolTipForm.validate({
                submitHandler : function(){
                    url = $noneSchoolTipForm.attr('action');
                    postData = $noneSchoolTipForm.serialize();
                    $submit = $noneSchoolTipForm.find('input[type=submit]');
                    if($submit.attr('data_lock')){
                        return false;
                    }
                    $submit.attr('data_lock',1).addClass('disable');
                    $.ajax({
                        url : url,
                        type: 'post',
                        data : postData,
                        dataType:'json',
                        success : function(r){
                            if(r.code == 0){
                                $schoolFeedBackTip.addClass('show');
                                setTimeout(function(){
                                    $schoolFeedBackTip.removeClass('show');
                                    $selectSchoolPop.fadeOut();
                                    $popMask.fadeOut();
                                },1000);
                            }else{
                                ajax_message(r.message,true);
                                setTimeout(function(){
                                    $ajaxMessageBox.fadeOut();
                                },1000);
                            }
                        },
                        error : function(){
                            ajax_message(errorHtml,true);
                            setTimeout(function(){
                                $ajaxMessageBox.fadeOut();
                            },1000);
                        },
                        complete:function(){
                            $submit.removeAttr('data_lock').removeClass('disable'); 
                        }
                    });
                    return false;
                }
            });
        });
    };
    _window.showFace = function(cid){// 初始化表情方法,参数cid为容器的选择器
        seajs.use('dist/jquery.qqFace/jquery.qqFace.js', function(){
            var $container,$content,$emo,len;
            len = $(cid).length;
            for(i=0;i<len;i++){
                $container = $(cid).eq(i);
                $content = $container.find('textarea.js_content');
                $emo = $container.find('.js_emo');
                $emo.qqFace({
                    $textarea: $content, 
                    path     : window.WJ_STA_DOMAIN+'/js/dist/jquery.qqFace/arclist/'
                });
            }
            
        });
    };
    _window.initRcInput = function(){//初始化单选、复选按钮方法
        var $jsRcInput = $('.js_rc_input').find('input');
        if($jsRcInput){
            seajs.use('dist/icheck.min.js',function(){
                $jsRcInput.iCheck({  // 模拟单选按钮,复选按钮
                    checkboxClass:'icheckbox',
                    radioClass:'iradio',
                    increaseArea:'20%'
                });
            });
        }
    }
    _window.extendDropdown = function(){//扩展下拉菜单方法
        var $html=$('html'),
            val;
        $html.off('click','.dropdown-toggle').on('click','.dropdown-toggle',function(){
            var $t = $(this);
            val = $t.find('input').val();
            $t.parent().find('a.dropdown-option').removeClass('active');
            $t.parent().find('ul.dropdown-menu a[value='+val+']').addClass('active');
        });
    };
})(window);


